package com.umeox.moto.watch.fitness.data;


import static com.umeox.moto.watch.fitness.utils.ICache.KEY_STEP_COUNT_TOTAL;

import android.util.Log;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.fitness.BuildConfig;
import com.umeox.moto.watch.fitness.utils.CacheImpl;
import com.umeox.moto.watch.fitness.utils.ICache;
import com.umeox.moto.watch.fitness.utils.StepManager;

import org.greenrobot.eventbus.EventBus;

public class PedometerNodeData implements PedometerDataSource {

    public static final int SENSOR_MAX_VALUE = 30000;
    private PedometerContract.Presenter mPresenter;
    private StepManager mStepManager;
    private static final String TAG = "PedometerData";
    private int mLastStepCounts;
    private final ICache mCache;
    private int mCacheStepCount;


    public PedometerNodeData(PedometerContract.Presenter presenter) {
        mPresenter = presenter;
        mStepManager = StepManager.getInstance();
        mCache = CacheImpl.getInstance();
        mCacheStepCount = mCache.get(KEY_STEP_COUNT_TOTAL, 0);

    }

    @Override
    public void load() {
        final int stepCounts = mStepManager.getStepCounts();
        if(BuildConfig.DEBUG){
            Log.w(TAG, "load: " + mLastStepCounts + " cur " + stepCounts + " CacheStepCount " + mCacheStepCount);
        }
        if (stepCounts != mLastStepCounts) {
            if (stepCounts - mCacheStepCount >= SENSOR_MAX_VALUE) {
                StepManager.getInstance().resetSensorFlag();
                mCache.put(KEY_STEP_COUNT_TOTAL, stepCounts);
                mCacheStepCount = stepCounts;
            }
            mLastStepCounts = stepCounts;
            mPresenter.onStepCountChange(stepCounts);
        }
    }




    @Override
    public void getStepInfo() {

    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {

    }

    @Override
    public void saveTotalStepCount() {
        final int curStepCount = StepManager.getInstance().getStepCounts() + mCacheStepCount;
        mCache.put(KEY_STEP_COUNT_TOTAL, curStepCount);
    }

    @Override
    public void resetAndSaveStepCount(int currentMillis, int saveTimeMillis) {
        Logger.e("==========resetAndSaveStepCount===============");
        ICache cache = CacheImpl.getInstance();
        //StepManager stepManager = StepManager.getInstance();
        cache.put(ICache.KEY_STEP_TIME, currentMillis);
        //stepManager.resetSensorFlag();
        cache.remove(KEY_STEP_COUNT_TOTAL);
        mCacheStepCount = 0;
        EventBus.getDefault().removeAllStickyEvents();
    }

}
